package com.ustc.hewei.detectbeats.config;

import com.ustc.hewei.detectbeats.detect.BeatsDetect;
import com.ustc.hewei.detectbeats.detect.SendBeat;
import com.ustc.hewei.detectbeats.net.ChannelNotifyHandler;
import com.ustc.hewei.detectbeats.net.NettyListener;
import com.ustc.hewei.detectbeats.net.NotifyHandler;
import com.ustc.hewei.rpc.propertise.RpcProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
* @description: 配置类
* @author hewei
* @date 2022/8/12 10:54
* @version 1.0
*/

@Configuration
public class AutoConfiguration {

    @Bean
    public BeatsDetect beatsDetect(@Autowired SendBeat sendBeat,
                                   @Autowired RpcProperties properties) {
        BeatsDetect beatsDetect = new BeatsDetect(sendBeat, properties.getDetectDelayTime());
        beatsDetect.start();
        return beatsDetect;
    }

    @Bean
    public ConcurrentHashMap<String, List<String>> map() {
        return new ConcurrentHashMap<>();
    }

    @Bean
    public NotifyHandler notifyHandler(@Autowired ConcurrentHashMap<String, List<String>> map,
                                       @Autowired SendBeat sendBeat) {
        return new NotifyHandler(map, sendBeat);
    }

    @Bean
    public ChannelNotifyHandler channelNotifyHandler(@Autowired NotifyHandler notifyHandler) {
        return new ChannelNotifyHandler(notifyHandler);
    }

    @Bean
    public NettyListener nettyListener(@Autowired ChannelNotifyHandler channelNotifyHandler,
                                       @Autowired RpcProperties properties) {
        String ip = properties.getRegisterCenterIp();
        NettyListener nettyListener = new NettyListener(channelNotifyHandler
                , Integer.parseInt(ip.substring(ip.indexOf(":") + 1)), properties.getProtocol());
        nettyListener.start();
        return nettyListener;
    }

    @Bean
    public SendBeat sendBeat(@Autowired RpcProperties properties,
                             @Autowired ConcurrentHashMap<String, List<String>> map) {
        return new SendBeat(map, properties.getProtocol(), properties.getMAX_COUNT());
    }
}
